package io.netty.client.core;

import io.netty.client.config.NettyClientConfig;
import io.netty.client.core.handler.ClientHandler;
import io.netty.client.core.handler.GlobalExceptionHandler;
import io.netty.client.core.heart.HeartBeatHandler;
import io.netty.client.server.connectScheduledTask;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class NettyClient extends AbstractNettyClient {
    @Resource
    private NettyClientConfig nettyClientConfig;
    @Resource
    private Executor taskExecutor;
    @PostConstruct
    public void start() {
        super.setConnServerIp(nettyClientConfig.getConnServerIp());
        super.setConnServerPort(nettyClientConfig.getConnServerPort());
        super.addLast(StringDecoder::new)
                .addLast(ClientHandler::new)
                .addLast(StringEncoder::new);
        //向链路注册写空闲监听器 + 写空闲时心跳保活
        final NettyClientConfig.KeepAlive keepAlive = nettyClientConfig.getKeepAlive();
        log.debug("config.keepAlive:{}", keepAlive);

        super.addLast("write-idle-handler",
                () -> {
                    return new IdleStateHandler(0, keepAlive.getWriteIdleMs(),
                            0, TimeUnit.MILLISECONDS);
                })
                .addLast("heartbeat-handler",
                        () -> {
                    return new HeartBeatHandler(keepAlive.getPingRetry(),
                            keepAlive.getPingTestContent());
                });
        super.addLast(connectScheduledTask::new);
        super.addLast(GlobalExceptionHandler::new);

        taskExecutor.execute(this);
    }

}
